﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Celeriq.ManagementStudio.EventArguments;
using Celeriq.Common;
using Celeriq.ManagementStudio.Objects;
using Celeriq.Client.Interfaces;

namespace Celeriq.ManagementStudio
{
	internal class ServiceThreader
	{
		private IRemotingObject _cache = null;
		private string _serverName = null;
		private UserCredentials _credentials = null;

		public ServiceThreader(string serverName, UserCredentials credentials)
		{
			_serverName = serverName;
			_credentials = credentials;
		}

		public ServiceThreader(string serverName, UserCredentials credentials, IRemotingObject cache)
			: this(serverName, credentials)
		{
			_cache = cache;
		}

		public event EventHandler<RepositoryEventArgs> RepositoryStarted;
		public event EventHandler<RepositoryEventArgs> RepositoryStopped;
		public event EventHandler<RepositoryErrorEventArgs> Error;

		protected virtual void OnRepositoryStarted(RepositoryEventArgs e)
		{
			if (this.RepositoryStarted != null)
				this.RepositoryStarted(this, e);
		}

		protected virtual void OnRepositoryStopped(RepositoryEventArgs e)
		{
			if (this.RepositoryStopped != null)
				this.RepositoryStopped(this, e);
		}

		protected virtual void OnError(RepositoryErrorEventArgs e)
		{
			if (this.Error != null)
				this.Error(this, e);
		}

		public void StartRepository()
		{
			try
			{
				using (var factory = SystemCoreInteractDomain.GetFactory(_serverName))
				{
					var server = factory.CreateChannel();
					_cache = server.StartRepository(_cache.Repository.ID, _credentials);
					this.OnRepositoryStarted(new RepositoryEventArgs() { Repository = _cache });
				}
			}
			catch (Exception ex)
			{
				this.OnError(new RepositoryErrorEventArgs() { Repository = _cache, Exception = ex });
			}
		}

		public void StopRepository()
		{
			try
			{
				using (var factory = SystemCoreInteractDomain.GetFactory(_serverName))
				{
					var server = factory.CreateChannel();
					_cache = server.StopRepository(_cache.Repository.ID, _credentials);
					this.OnRepositoryStopped(new RepositoryEventArgs() { Repository = _cache });
				}
			}
			catch (Exception ex)
			{
				this.OnError(new RepositoryErrorEventArgs() { Repository = _cache, Exception = ex });
			}
		}

	}
}
